package com.backend.utils;

import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;


/**
 * @author HUJIAMIN
 * @since 2020/11/6
 */
public class WxCryptUtils {

  /**
   * 小程序 数据解密
   *
   * @param encryptData 加密数据
   * @param iv          对称解密算法初始向量
   * @param sessionKey  对称解密秘钥
   * @return 解密数据
   */
  public static String decrypt(String encryptData, String iv, String sessionKey) throws Exception {
    AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance("AES");
    algorithmParameters.init(new IvParameterSpec(Base64.decodeBase64(iv)));
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES"),
      algorithmParameters);
    byte[] decode = PKCS7Encoder.decode(cipher.doFinal(Base64.decodeBase64(encryptData)));
    String decryptStr = new String(decode, StandardCharsets.UTF_8);
    return decryptStr;
  }

  /**
   * 数据加密
   *
   * @param data       需要加密的数据
   * @param iv         对称加密算法初始向量
   * @param sessionKey 对称加密秘钥
   * @return 加密数据
   */
  public static String encrypt(String data, String iv, String sessionKey) throws Exception {
    AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance("AES");
    algorithmParameters.init(new IvParameterSpec(Base64.decodeBase64(iv)));
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES"),
      algorithmParameters);
    byte[] textBytes = data.getBytes(StandardCharsets.UTF_8);
    ByteGroup byteGroup = new ByteGroup();
    byteGroup.addBytes(textBytes);
    byte[] padBytes = PKCS7Encoder.encode(byteGroup.size());
    byteGroup.addBytes(padBytes);
    byte[] encryptBytes = cipher.doFinal(byteGroup.toBytes());
    return Base64.encodeBase64String(encryptBytes);
  }


  public static void main(String[] args) throws Exception {
    // 微信 小程序的 测试数据
    String encrypt = "JTn6AfmGlrns4r8MdwokI3WeO8mxuIceCiO21BQbULuc4YR+XHzZqYFHUoBZr2sqPdSY1kvQpaEc9JO31U56UurRlPpIa07HF4Z7Y5Oob9QBoG64+CrvEgvGt/h5/18Yze8WfN7+Ae9yoEpu5RudvV7xclrc6jUzyVHAJj7pRgWomAW4ntQuliUOKsI0ncIPkSEa1pE4CmNZV+PP/D1j3A==";

    String sessionKey = "1JvhN+m5NlbX5nOLCx8hqQ==";
    String iv = "kk6ivexUrcguj91ok4dM3g==";

    String decrypt = WxCryptUtils.decrypt(encrypt, iv, sessionKey);
    System.out.println(decrypt);
  }

}
